package org.base.common.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.base.common.exception.BusinessException;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Set;
import java.util.function.Consumer;

/**
 * @author He mingliang
 */
@Slf4j
public class DataListener<T> extends AnalysisEventListener<T> {

    private Consumer<T> consumer;

    private Validator validator;

    public DataListener(Consumer<T> consumer, Validator validator) {
        this.consumer = consumer;
        this.validator = validator;
    }

    @Override
    public void invoke(T data, AnalysisContext context) {
        log.debug("data {}", data);
        if (validator != null) {
            final Set<ConstraintViolation<T>> constraintViolations = validator.validate(data, Default.class);
            if (CollectionUtils.isNotEmpty(constraintViolations)) {
                Integer rowIndex = context.readRowHolder().getRowIndex() + 1;
                StringBuilder stringBuilder = new StringBuilder("第" + rowIndex + "行，");
                constraintViolations.forEach(c -> stringBuilder.append(c.getPropertyPath() + ": " + c.getMessage() + "; "));
                throw new BusinessException(stringBuilder.toString());
            }
            consumer.accept(data);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }
}
